"""
使用urllib2请求代理服务器
请求http和https网页均适用
"""
import urllib2
import ssl
import time

# 应用账号（请替换为真实账号）
app_key = 'app_key'
# 应用密码（请替换为真实密码）
app_secret = 'app_secret'

api_url = "https://api.xiaoxiangdaili.com/ip/get"


def getProxy():
    url = api_url + "?appKey=" + app_key + "&appSecret=" + app_secret + "&cnt=1&wt=text"
    # 获取API接口返回的IP
    proxy_ip = urllib2.urlopen(url).read()
    return proxy_ip


def getUrlContent(target_url):
    p = getProxy()
    # 如需使用socks5代理，只需将下面http替换为socks5h即可
    proxyMeta = "http://%(user)s:%(pass)s@%(proxy)s" % {
        "proxy": p,
        "user": app_key,
        "pass": app_secret,
    }
    proxies = {
        'http': proxyMeta,
        'https': proxyMeta,
    }
    try:
        # 使用代理IP发送请求
        proxy_support = urllib2.ProxyHandler(proxies)
        opener = urllib2.build_opener(proxy_support)
        urllib2.install_opener(opener)
        response = urllib2.urlopen(target_url)
    except Exception as e:
        print(e)
    else:
        print(response.read())

# 全局取消证书验证，避免访问https网页报错
ssl._create_default_https_context = ssl._create_unverified_context

target_url = "http://httpbin.org/ip"
for i in range(5):
    getUrlContent(target_url)
    time.sleep(10)